package com.playwright.xhs.grab;

import com.microsoft.playwright.*;
import com.microsoft.playwright.options.AriaRole;
import com.microsoft.playwright.options.KeyboardModifier;

import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.List;

/**
 * @author liyanhao
 * @Date 2024-06-04 17:43
 */
public class grab {
    public static void main(String[] args) throws InterruptedException {

        String key = "比亚迪";

        try (Playwright playwright = Playwright.create()) {
            BrowserType.LaunchOptions launchOptions = new BrowserType.LaunchOptions();
            launchOptions.setExecutablePath(Path.of("C:\\Users\\lyh\\AppData\\Local\\Google\\Chrome\\Application\\chrome.exe"));
            launchOptions.setHeadless(false).setSlowMo(500);
            Browser browser = playwright.chromium().connectOverCDP("http://localhost:9222");
            //保存登录态
            String statePath = Paths.get("D:\\IdeaProjects\\JavaTechnologyLearn\\_8106-playwright\\src\\main\\java\\com\\playwright\\xhs\\auth\\xhs_auth.json").toString();
            BrowserContext.StorageStateOptions options = new BrowserContext.StorageStateOptions();
            options.setPath(Paths.get(statePath));
            // 加载之前保存的浏览器状态以保持登录状态
            BrowserContext context = browser.newContext(new Browser.NewContextOptions()
                    .setStorageStatePath(Paths.get(statePath)));

            //搜索关键字
            Page page = context.newPage();
            page.navigate("https://www.xiaohongshu.com/explore");
            page.getByPlaceholder("搜索小红书").click();
            page.getByPlaceholder("搜索小红书").fill(key);
            page.getByPlaceholder("搜索小红书").press("Enter");

            List<ElementHandle> elementHandles = page.querySelectorAll(".cover.ld.mask");
            for (int i = 0; i < 40; i++) {
                ElementHandle elementHandle = elementHandles.get(i);
                ElementHandle elementHandle1 = elementHandle.querySelector("img");
                elementHandle1.click();
                Thread.sleep(1000);
                System.out.println(page.url());
                page.locator(".close > .reds-icon").click(new Locator.ClickOptions()
                        .setModifiers(Arrays.asList(KeyboardModifier.CONTROL)));
            }
            Thread.sleep(1000000000);
        }
    }




}
